/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { useSelector } from 'umi';
import DragTable from '@/components/DragTable';
import { Modal, Form, Input, message, Space, Popconfirm, Button } from 'antd';
import { updateMaterial, getNewHelpList, deleteNewHelp } from '@/services/news/help';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import KbImage from '@/components/KbImage';
import type { ConnectState } from '@/models/connect';
import type { TableColumns } from './index.d';
import styles from './index.less';
import UploadWithCrypto from '@base/components/upload-width-crypto';

const AdminUser: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [filesList, setFilesList] = useState<any[]>([]);
  const [record, setRecord] = useState<any>({});

  const handleChange = (file: any) => {
    const { fileList } = file;
    if (filesList.length > fileList.length) {
      setFilesList(fileList);
    }
  };

  const onSuccess = (data: any) => setFilesList([...filesList, { url: data.data }]);
  const handleOk = () => formRef.current?.submit();
  const handleModalChancel = () => setVisible(false);

  const onSubmit = async (data: any) => {
    delete data.files;
    if (filesList.length < 1) {
      message.error('图片最少上传一张');
      return;
    }
    const imgList = filesList.map((item: any) => item.url);
    data.pic_path = JSON.stringify(imgList);
    if (record.id) {
      data.id = record.id;
    }
    const { code, msg } = await updateMaterial(data);
    if (code === 0) {
      setRecord({});
      setVisible(false);
      actionRef.current?.reload();
    } else {
      message.error(msg);
    }
  };

  const deleteNewHelps = async (data: any) => {
    const { code, msg } = await deleteNewHelp({ id: data.id });
    if (code == 0) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.error(msg);
    }
  };

  const handleModalOpen = (data: any) => {
    if (data.id) {
      setRecord(data);
      const filesLists = data.pic_path.map((item: any, index: number) => ({
        uid: index,
        url: item,
      }));
      setFilesList(filesLists);
    } else {
      setFilesList([]);
      setRecord({});
    }
    setVisible(true);
  };

  const checkFileSize = (file: any) => {
    const { size, type } = file;
    const isLt5M = size / 1024 / 1024 < 5;
    const fileType = type.split('/')[1];
    const hasAccept = ['jpeg', 'png', 'jpg'].includes(fileType);

    if (!isLt5M) {
      message.error('图片尺寸大于5M');
      return false;
    } else if (!hasAccept) {
      message.error('仅支持png、jpg格式');
      return false;
    } else {
      return true;
    }
  };

  const fetchTableList = (params: any) => {
    const { current: page } = params;
    return getNewHelpList({ page, page_size: 20 });
  };

  const uploadButton = (
    <div style={{ color: '#4ca4f8' }}>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>点击上传素材</div>
    </div>
  );

  const columns: ProColumns<TableColumns>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      search: false,
      width: 80,
    },
    {
      title: '标题',
      dataIndex: 'title',
      align: 'center',
      search: false,
      width: 120,
    },
    {
      title: '图片',
      dataIndex: 'pic_path',
      align: 'center',
      search: false,
      width: 120,
      render: (data: any) => {
        return (
          <Space>
            {' '}
            {data.map((item: any, index: number) => {
              return <KbImage width={30} height={30} key={index + 1} src={`${item}`} />;
            })}
          </Space>
        );
      },
    },
    {
      title: '操作',
      align: 'center',
      search: false,
      valueType: 'option',
      dataIndex: 'option',
      fixed: 'right',
      width: winSize === 'xs' ? 40 : 80,
      render: (_, data) => {
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <a onClick={handleModalOpen.bind(this, data)}>修改</a>
            <Popconfirm title='确定删除？' onConfirm={deleteNewHelps.bind(this, data)}>
              <a>删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <DragTable>
        <ProTable<TableColumns>
          className={styles.table}
          actionRef={actionRef}
          request={fetchTableList}
          rowKey='id'
          columns={columns}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          options={false}
          search={{
            collapsed: false,
            optionRender: () => [
              <Button key='12' type='primary' onClick={handleModalOpen}>
                添加物料
              </Button>,
            ],
          }}
          scroll={{ x: 640 }}
        />
      </DragTable>
      <Modal
        visible={visible}
        title={record.id ? '修改物料' : '添加物料'}
        destroyOnClose
        onCancel={handleModalChancel}
        footer={[
          <Button type='primary' key={11} onClick={handleOk}>
            {record.id ? '保存修改' : '提交'}
          </Button>,
        ]}
      >
        <Form ref={formRef} onFinish={onSubmit} initialValues={record}>
          <Form.Item
            name='title'
            label='物料标题'
            rules={[{ required: true, message: '请输入物料标题' }]}
          >
            <Input placeholder='请输入物料标题，不超过20个字' maxLength={20} allowClear />
          </Form.Item>
          <Form.Item
            name='files'
            label='上传素材'
            help='支持png、jpg格式，大小不超过5M，最多上传3张'
            style={{ marginLeft: 10 }}
            validateTrigger={filesList}
          >
            <UploadWithCrypto
              action='/Inn/uploadWuLiao'
              listType='picture-card'
              accept='.jpg,.png'
              multiple={false}
              fileList={filesList}
              onChange={handleChange}
              onSuccess={onSuccess}
              beforeUpload={checkFileSize}
              showUploadList={{ showPreviewIcon: false }}
            >
              {filesList.length >= 3 ? null : uploadButton}
            </UploadWithCrypto>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default AdminUser;
